package com.sike.service;

import com.sike.entity.Order;
import com.sike.entity.OrderItem;
import com.sike.mapper.OrderMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

/**
 * @author vito
 * @version 1.0
 */
@Service
public class OrderService {

    public static final Logger logger = LoggerFactory.getLogger(OrderService.class);
    @Autowired
    private UserService userService;

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private CartService cartService;

    @Autowired
    private OrderItemService orderItemService;

    @Transactional
    public void createOrder(Order order) {
        logger.info("订单对象详情: {}", order);
        try {
            logger.info("尝试创建订单: {}", order);
            logger.debug("订单对象: {}", order);

            if (order.getOrderItems() == null || order.getOrderItems().isEmpty()) {
                throw new IllegalArgumentException("订单物品不能为空");
            }

            // 输出订单项信息
            for (OrderItem item : order.getOrderItems()) {
                logger.debug("订单项: {}", item);
            }

            order.setUserId(1);
            orderMapper.createOrder(order); // 创建订单获取订单ID

            // 计算订单总价
            BigDecimal totalPrice = order.getOrderItems().stream()
                    .map(item -> item.getPrice().multiply(new BigDecimal(item.getQuantity())))
                    .reduce(BigDecimal.ZERO, BigDecimal::add);
            order.setTotalPrice(totalPrice); // 设置订单总价

            // 处理订单项
            for (OrderItem item : order.getOrderItems()) {
                item.setOrderId(order.getId());
                orderItemService.addOrderItem(item);
                cartService.removeCartItem(order.getUserId(), item.getDrugId());
            }

            logger.info("订单总价: {}", order.getTotalPrice());

            // 更新用户余额，扣除订单总价
            userService.updateBalance(order.getUserId(), order.getTotalPrice().negate());

            logger.info("订单创建成功: {}", order);
        } catch (Exception e) {
            logger.error("创建订单时出错: ", e);
            throw e;
        }
    }





    // 取消订单
    @Transactional
    public void cancelOrder(Integer orderId) {
        try {
            Order order = orderMapper.findById(orderId);
            //打印订单信息
            System.out.println("订单信息: " + order);
            if (order != null) {
                // 先将订单状态改变为已取消
                orderMapper.cancelOrder(orderId);

                // 获取订单总价
                System.out.println("1订单总价: " + order.getTotalPrice() + "元");
                BigDecimal totalPrice = order.getTotalPrice();
                System.out.println("2订单总价: " + totalPrice);

                // 如果订单总价不为空且大于0，返还用户余额
                if (totalPrice != null && totalPrice.compareTo(BigDecimal.ZERO) > 0) {
                    // 获取订单对应的用户ID
                    Integer userId = order.getUserId();
                    // 返还用户余额
                    userService.updateBalance(userId, totalPrice);
                    logger.info("订单已成功取消，用户余额已返还: 用户ID={}, 返还金额={}", userId, totalPrice);
                } else {
                    logger.warn("订单总价为空或小于等于0，无需返还余额");
                }
            } else {
                // 如果订单为空
                logger.error("未找到订单，订单ID: {}", orderId);
            }
        } catch (Exception e) {
            logger.error("取消订单时出错: ", e);
            throw e;
        }
    }



    // 获取所有订单
    public List<Order> findAllOrders() {
        return orderMapper.findAllOrders();
    }

    // 获取订单详情，包括订单项
    public Order getOrderDetails(Integer orderId) {
        Order order = orderMapper.findById(orderId);
        if (order != null) {
            List<OrderItem> items = orderItemService.getOrderItemsByOrderId(orderId);
            // 设置订单的订单项
            order.setOrderItems(items);
        }
        return order;
    }
}
